import request from '../request'

// 对话完成API - 集成GLM-4.5模型
export async function chatCompletion(message: string, options: {stream?: boolean, temperature?: number, max_tokens?: number} = {}) {
  try {
    console.log("正在提交GLM-4.5对话请求...");
    // 生成请求ID
    const requestId = `req-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
    
    const response = await request.post(
      '/paas/v4/chat/completions',
      {
        model: 'glm-4.5',
        messages: [
          { role: 'user', content: message }
        ],
        request_id: requestId,
        do_sample: true,
        stream: options.stream !== undefined ? options.stream : false,  // 默认关闭流式
        thinking: {
          type: 'enabled',
        },
        temperature: options.temperature !== undefined ? options.temperature : 0.6,  // API默认值0.6
        top_p: 0.95,  // API默认值
        max_tokens: options.max_tokens !== undefined ? options.max_tokens : 1024  // API建议不小于1024
      },
      {
        baseURL: 'https://open.bigmodel.cn/api',
        timeout: 30000,
        responseType: options.stream ? 'stream' : 'json'
      }
    )

    // 处理响应数据
    if (options.stream) {
      // 流式响应处理
      console.log("✅ GLM-4.5流式对话请求成功!");
      return {
        success: true,
        data: response.data,
        requestId: requestId
      };
    } else if (response.data && response.data.choices && response.data.choices.length > 0) {
      // 非流式响应处理
      const choice = response.data.choices[0];
      const reply = choice.message?.content || '无响应内容';
      console.log("✅ GLM-4.5对话请求成功!");
      return {
        success: true,
        data: {
          reply,
          finishReason: choice.finish_reason,
          usage: response.data.usage
        },
        requestId: requestId
      };
    } else {
      console.log("❌ GLM-4.5对话请求失败: 返回数据格式不正确");
      return {
        success: false,
        message: "GLM-4.5对话请求失败: 返回数据格式不正确",
        rawData: response.data,
        requestId: requestId
      };
    }
  } catch (error) {
    console.error("❌ GLM-4.5对话请求失败:", error);
    console.error("错误详情:", (error as any).config);
    console.error("响应状态:", (error as any).response?.status);
    console.error("响应数据:", (error as any).response?.data);
    
    return {
      success: false,
      message: `GLM-4.5对话请求失败: ${(error as any).message || '未知错误'}`,
      errorCode: (error as any).response?.status || 'unknown',
      errorDetails: (error as any).response?.data || {},
      error: error
    };
  }
}